package com.anysoft.webloader;

import com.anysoft.util.KeyGen;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import javax.servlet.http.HttpServletRequest;

/**
 * Trace相关的工具
 */
public class HttpTraceTool {
    protected String TraceId = "X-Trace-Id";
    protected String TraceOrder = "X-Trace-Order";
    protected boolean mdcEnable = true;
    protected String mdcKey = "X-Trace-Id";

    public HttpTraceTool(Properties p){
        TraceId = PropertiesConstants.getString(p,"http.traceId",TraceId);
        TraceOrder = PropertiesConstants.getString(p,"http.traceOrder",TraceOrder);
        mdcEnable = PropertiesConstants.getBoolean(p,"mdc.enable",mdcEnable);
        mdcKey = PropertiesConstants.getString(p,"mdc.key",mdcKey);
    }

    public String getTraceId(HttpServletRequest request) {
        String header = getRequestHeader(request,TraceId);
        if (StringUtils.isAlphanumeric(header) && header.length() <= 32){
            return header;
        }
        return KeyGen.uuid(8, 0, 15);
    }

    public String getTraceOrder(HttpServletRequest request) {
        String header = getRequestHeader(request,TraceOrder);
        if (StringUtils.isAlphanumeric(header) && header.length() <= 32){
            return header;
        }
        return "1";
    }

    public String getRequestHeader(HttpServletRequest request,String id) {
        return request.getHeader(id);
    }

    public boolean enableMDC(String sn){
        if (mdcEnable){
            MDC.put(mdcKey,sn);
        }
        return mdcEnable;
    }
}
